package com.ytkj.digitalConstruction.service.user;

import static com.ytkj.digitalConstruction.util.ExcelUtils.getMergedRegionValue;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import com.alibaba.druid.util.StringUtils;
import com.alibaba.fastjson.JSONObject;
import com.ytkj.digitalConstruction.dao.base.ConfigMapper;
import com.ytkj.digitalConstruction.dao.dept.DeptMapper;
import com.ytkj.digitalConstruction.dao.dept.DeptUserMapper;
import com.ytkj.digitalConstruction.dao.role.RoleMapper;
import com.ytkj.digitalConstruction.dao.role.UserGroupRoleMapper;
import com.ytkj.digitalConstruction.dao.role.UserRoleMapper;
import com.ytkj.digitalConstruction.dao.user.UserGroupUserMapper;
import com.ytkj.digitalConstruction.dao.user.UserMapper;
import com.ytkj.digitalConstruction.entity.base.Config;
import com.ytkj.digitalConstruction.entity.dept.Dept;
import com.ytkj.digitalConstruction.entity.dept.DeptUser;
import com.ytkj.digitalConstruction.entity.role.Role;
import com.ytkj.digitalConstruction.entity.role.UserRole;
import com.ytkj.digitalConstruction.entity.user.User;
import com.ytkj.digitalConstruction.enums.dept.DeptTypeEnum;
import com.ytkj.digitalConstruction.enums.ding.DingOperationEnum;
import com.ytkj.digitalConstruction.enums.role.RoleNameEnum;
import com.ytkj.digitalConstruction.enums.user.ConstantUserField;
import com.ytkj.digitalConstruction.enums.user.UserPhotoEnum;
import com.ytkj.digitalConstruction.enums.user.UserRedisKeyPrefixEnum;
import com.ytkj.digitalConstruction.enums.user.UserStatusEnum;
import com.ytkj.digitalConstruction.httpbean.dept.req.ReqDept;
import com.ytkj.digitalConstruction.httpbean.user.ReqUser;
import com.ytkj.digitalConstruction.httpbean.user.req.AddOrUpdateDingUser;
import com.ytkj.digitalConstruction.httpbean.user.req.ReqDingUser;
import com.ytkj.digitalConstruction.httpbean.user.resbean.UserDeptId;
import com.ytkj.digitalConstruction.httpbean.user.resbean.UserDetails;
import com.ytkj.digitalConstruction.httpbean.user.resbean.UserRoleBean;
import com.ytkj.digitalConstruction.rabbit.BaseVar;
import com.ytkj.digitalConstruction.rabbit.Sender;
import com.ytkj.digitalConstruction.redis.RedisHashService;
import com.ytkj.digitalConstruction.redis.RedisObjectService;
import com.ytkj.digitalConstruction.service.constructionprocess.ConstructionBaseService;
import com.ytkj.digitalConstruction.service.dept.DeptService;
import com.ytkj.digitalConstruction.service.role.RoleService;
import com.ytkj.digitalConstruction.util.ExcelUtils;
import com.ytkj.digitalConstruction.util.MD5;
import com.ytkj.digitalConstruction.util.PinYinUtil;
import com.ytkj.digitalConstruction.util.WebTokenUtil;

/**
 * 用户业务处理类
 * 
 * @author Pete
 * @author momei
 * @Date 2017年12月7日
 */
@Service
@Transactional
public class UserService {
	Logger log = LoggerFactory.getLogger(getClass());

	@Autowired
	private UserMapper userMapper;

	@Autowired
	private DeptUserMapper deptUserMapper;
	@Autowired
	private UserRoleMapper userRoleMapper;
	@Autowired
	private ConfigMapper configMapper;
	@Autowired
	private ConstructionBaseService constructionBaseService;
	@Autowired
	private DeptMapper deptMapper;
	@Autowired
	private RoleMapper roleMapper;

	@Autowired
	private DeptService deptService;
	@Autowired
	private RoleService roleService;
	@Autowired
	private Sender sender;
	@Autowired
	private BaseVar baseVar;
	@Autowired
	private RedisObjectService<String> redisObjStringService;
	@Autowired
	private RedisHashService<User> redisHashUserService;
	@Autowired
	private RedisHashService<LinkedHashMap<String, Object>> redisHashMapService;
	@Autowired
	private UserGroupUserMapper userGroupUserMapper;
	@Autowired
	private  UserGroupRoleMapper userGroupRoleMapper;
	/** 用户登录信息过期时间 */
	private final static long LOGIN_EXPIRE = -1L;

	/**
	 * 新增用户
	 * 
	 * @param reqUser
	 * @return 若成功返回空字符串，失败，返回错误消息
	 */
	public String addUser(ReqUser reqUser) {
		User user = reqUser.user();
		//新增， 根据用户名、手机号和状态为可用查询改用户是否存在，存在提示，不存在新建；
		User existUser = userMapper.selectByUserNameAndMobile(user.getUserName(), user.getMobile());
		if (existUser != null) {
			user = existUser;
			user.setStatus(UserStatusEnum.ABLE.getValue());
			user.setPasswd(ConstantUserField.DEFAULT_PASSWORD);
			userMapper.updateByPrimaryKeySelective(user);
		} else {
			user.setStatus(UserStatusEnum.ABLE.getValue());
			// 获取用户头像图片地址
			Config config = configMapper.selectByPrimaryKey(UserPhotoEnum.HEAD_URL_ID.getValue());
			if (config != null) {
				// 设置默认头像
				user.setHeadUrl(config.getValue());
			}
			if (StringUtils.isEmpty(user.getPasswd())) {
				// 设置默认密码
				user.setPasswd(ConstantUserField.DEFAULT_PASSWORD);
			}
			user.setPasswd(MD5.md5(user.getPasswd()));
			if (userMapper.insertSelective(user) < 1) {
				log.error("UserService addUser Exception: userMapper.insertSelective faild!");
				// 添加失败
				return "数据库添加失败！";
			}
		}

		// 向redis中添加用户
		redisHashUserService.put(UserRedisKeyPrefixEnum.USER.getValue() + user.getUserId(), "user", user, LOGIN_EXPIRE);

		// 向用户角色关系表中添加数据
		UserRole userRole = new UserRole();
		reqUser.setRoleIds(uniq(reqUser.getRoleIds()));
		for (Integer i : reqUser.getRoleIds()) {
			userRole.setId(null);
			userRole.setUserId(user.getUserId());
			userRole.setRoleId(i);
			userRoleMapper.insertSelective(userRole);
		}
		// 向用户部门关系表中添加数据
		DeptUser deptUser = new DeptUser();
		reqUser.setDeptIds(uniq(reqUser.getDeptIds()));
		for (Integer i : reqUser.getDeptIds()) {
			deptUser.setId(null);
			deptUser.setUserId(user.getUserId());
			deptUser.setDeptId(i);
			deptUserMapper.insertSelective(deptUser);
		}
		// 向钉钉添加用户
		reqUser.setUserId(user.getUserId());
		String dingMsg = addOrUpdateToDing(reqUser, DingOperationEnum.CREATE.getValue());
		if (!StringUtils.isEmpty(dingMsg)) {
			log.error("UserService addUser Exception: add user to ding faild!");
			return dingMsg;
		}
		return "";
	}

	/**
	 * 向钉钉中添加或修改用户
	 * 
	 * @param reqUser
	 * @return
	 * @throws Exception
	 */
	private String addOrUpdateToDing(ReqUser reqUser, String type) {
		AddOrUpdateDingUser user = addOrUpdateDingUser(reqUser, type);
		String msg = JSONObject.toJSONString(user);
		String response = sender.send(msg, baseVar.getRoutingkeyUser());
		if (JSONObject.parseObject(response).getBooleanValue("success") == false) {
			log.error("UserService addOrUpdateToDing Exception: " + JSONObject.parseObject(response).getString("msg"));
			TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
			return "钉钉消息：" + JSONObject.parseObject(response).getString("msg");
		}
		return "";

	}

	/**
	 * 封装添加或修改时需要向后台传的对象
	 * 
	 * @param reqUser
	 * @return
	 */
	private AddOrUpdateDingUser addOrUpdateDingUser(ReqUser reqUser, String type) {
		AddOrUpdateDingUser user = new AddOrUpdateDingUser();
		user.setType(type);
		ReqDingUser dingUser = new ReqDingUser();
		dingUser.setUserid(reqUser.getUserId());
		dingUser.setName(reqUser.getName());
		dingUser.setMobile(reqUser.getMobile());
		dingUser.setDepartment(reqUser.getDeptIds());
		dingUser.setPosition(reqUser.getPosition());
		dingUser.setIsManager(reqUser.getIsManager());
		user.setUser(dingUser);
		return user;
	}

	/**
	 * 删除用户，逻辑删除，不删除关联关系
	 * @param userId
	 * @return
	 */
	public boolean deleteUser(int userId) {
		if (userMapper.deleteByPrimaryKeyLogically(userId) < 1) {
			log.error("UserService deleteUser Exception: 从数据库删除用户，失败!");
			return false;
		}
		// 从redis中删除用户
		redisHashUserService.remove(UserRedisKeyPrefixEnum.USER.getValue() + userId, "user");
		// 删除user-role 关联关系
		//userRoleMapper.deleteByUserId(userId);
		// 删除user-dept 关联关系
		//deptUserMapper.deleteByUserId(userId);

		// 从钉钉中删除
		AddOrUpdateDingUser user = new AddOrUpdateDingUser();
		ReqDingUser reqDingUser = new ReqDingUser();
		user.setType("delete");
		reqDingUser.setUserid(userId);
		user.setUser(reqDingUser);

		String msg = JSONObject.toJSONString(user);
		String response = sender.send(msg, baseVar.getRoutingkeyUser());
		if (JSONObject.parseObject(response).getBooleanValue("success") == false) {
			log.error("UserService deleteUser Exception: 从钉钉删除用户失败！");
			// throw new CustomException(DingExceptionEnum.DELETE_ERROR);
		}
		return true;
	}

	/**
	 * 修改用户
	 * 
	 * @param reqUser
	 * @return 成功是返回空字符串,失败时返回失败信息
	 */
	public String updateUser(ReqUser reqUser) {
		User user = reqUser.user();

		if (userMapper.selectByPrimaryKey(user.getUserId()) == null) {
			return "需要操作的对象不存在！";
		}
		if (!StringUtils.isEmpty(user.getPasswd())) {
			user.setPasswd(MD5.md5(user.getPasswd()));

			// 重置密码
		} else if ("".equals(user.getPasswd())) {
			user.setPasswd(MD5.md5(ConstantUserField.DEFAULT_PASSWORD));
		}
		// 修改用户对象
		if (userMapper.updateByPrimaryKeySelective(user) < 1) {
			return "修改数据库失败！";
		}
		// 向redis中添加用户
		redisHashUserService.put(UserRedisKeyPrefixEnum.USER.getValue() + user.getUserId(), "user", user, LOGIN_EXPIRE);

		// 修改用户角色
		if (roleService.updateUserRoles(user.getUserId(), uniq(reqUser.getRoleIds())) == false) {
			return "修改数角色失败！";
		}
		// 修改用户部门
		if (updateUserDept(user.getUserId(), uniq(reqUser.getDeptIds())) == false) {
			return "修改部门失败！";
		}
		// 钉钉修改用户
		String dingMsg = addOrUpdateToDing(reqUser, DingOperationEnum.UPDATE.getValue());
		if (!StringUtils.isEmpty(dingMsg)) {
			return dingMsg;
		}

		return "";
	}

	/**
	 * 修改用户的部门
	 * 
	 * @param userId
	 * @param deptIds
	 * @return
	 */
	private boolean updateUserDept(Integer userId, List<Integer> deptIds) {
		List<DeptUser> deptUsers = deptUserMapper.selectByUserId(userId);
		List<Integer> existsDeptIds = new ArrayList<>();
		deptUsers.stream().forEach(o -> existsDeptIds.add(o.getDeptId()));
		// 之前有的现在没有的
		List<Integer> needDelIds = new ArrayList<>();
		for (int i : existsDeptIds) {
			if (deptIds.contains(i)) {
				continue;
			}
			needDelIds.add(i);
		}
		if (!needDelIds.isEmpty()) {
			deptUserMapper.delByUserIdAndDeptIds(userId, needDelIds);
		}
		// 添加之前没有的角色
		DeptUser deptUser = new DeptUser();
		deptUser.setUserId(userId);
		for (int i : deptIds) {
			if (existsDeptIds.contains(i)) {
				continue;
			}
			deptUser.setId(null);
			deptUser.setDeptId(i);
			deptUserMapper.insertSelective(deptUser);
		}

		// 新增之前没有的部门
		return true;
	}

	/**
	 * 获取用户所有部门信息
	 * 
	 * @param userId
	 * @return
	 */
	public List<Map<String, Object>> getDepts(Integer userId) {
		List<DeptUser> deptUsers = deptUserMapper.selectByUserIdAndDeptType(userId, DeptTypeEnum.DEPT.getValue());
		List<Map<String, Object>> list = new ArrayList<>();
		for (DeptUser du : deptUsers) {
			Map<String, Object> map = deptService.getDeptTree(du.getDeptId());
			list.add(map);
		}
		return list;
	}

	/**
	 * 用户登录，成功：返回webToken
	 * 
	 * @param userName
	 * @param passwd
	 * @return
	 */
	public String login(String userName, String passwd) {
		passwd = MD5.md5(passwd);
		User user = userMapper.selectByUnameAndPasswd(userName, passwd);
		if (user == null) {
			log.error("UserService login Exception: 无该用户！");
			return null;
		}
		if (getUserByUserIdFromRedis(user.getUserId()) == null) {
			log.info("向redis中添加用户对象！");
			redisHashUserService.put(UserRedisKeyPrefixEnum.USER.getValue() + user.getUserId(), "user", user,
					LOGIN_EXPIRE);
		}
		String redisKey = UserRedisKeyPrefixEnum.USER_ID.getValue() + user.getUserId();
		String webToken = WebTokenUtil.getWebToken("userId", user.getUserId());
		redisObjStringService.set(redisKey, webToken);
		return webToken;
	}

	/**
	 * 判断手机号是否已注册
	 * 
	 * @param mobile
	 * @return
	 */
	public boolean isExistedMobile(String mobile) {
		return userMapper.selectByMobile(mobile).size() > 0;
	}

	public boolean isExistedUserName(String userName) {
		return userMapper.selectByUserName(userName).size() > 0;
	}

	/**
	 * 手机端登录
	 * 
	 * @param userId
	 * @return
	 */
	public String webToken(Integer userId) {
		User user = userMapper.selectByPrimaryKey(userId);
		if (user == null) {
			log.error("UserService webToken Exception: 用户不存在！");
			return null;
		}
		String webToken = WebTokenUtil.getWebToken("userId", userId);
		redisObjStringService.set(UserRedisKeyPrefixEnum.USER_ID.getValue() + userId, webToken);
		return webToken;

	}

	/**
	 * 根据webToken拿到用户对象
	 * 
	 * @param webToken
	 * @return 根据webToken拿到的用户对象，若获取失败返回 null
	 */
	public UserDetails getUserByWebToken(String webToken) {
		Integer userId = (Integer) WebTokenUtil.parseWebToken(webToken, "userId");
		UserDetails details = null;
		String token = redisObjStringService.get(UserRedisKeyPrefixEnum.USER_ID.getValue() + userId);
		if (StringUtils.isEmpty(token)) {
			log.error("userService getUserByWebToken Exception: 登录验证失败！");
			return null;
		}
		User user = null;

		// 从redis中查询
		// user = getUserByUserIdFromRedis(userId);
		user = userMapper.selectByPrimaryKey(userId);
		if (user != null) {
			details = userToUserDetails(user);
			// 实体部门
			List<Integer> realDeptId = deptUserMapper.selectDeptIdByUserIdAndDeptType(user.getUserId(),
					DeptTypeEnum.DEPT.getValue());
			if (!realDeptId.isEmpty()) {
				Dept dept = deptMapper.selectByPrimaryKey(realDeptId.get(0));
				if (dept != null) {
					details.setRealDeptName(dept.getDeptName());
				}
			}
			// 角色ids
			List<Integer> roleIds = userRoleMapper.selectRoleIdByUserId(user.getUserId());
			String roleNames = roleNames(roleIds);
			details.setRoleNames(roleNames);
		}
		return details;

	}

	/**
	 * 将指定id数组角色名以逗号间隔的形式返回，如："name1,name2,name3"
	 * 
	 * @param roleIds
	 * @return
	 */
	private String roleNames(List<Integer> roleIds) {
		List<Role> roles = roleMapper.selectByIds(roleIds);
		String roleNames = "";
		for (Role role : roles) {
			roleNames += role.getRoleName() + ",";
		}
		return roleNames.substring(0, roleNames.length() - 1);
	}

	private UserDetails userToUserDetails(User user) {
		String jsonStr = JSONObject.toJSONString(user);
		return JSONObject.parseObject(jsonStr, UserDetails.class);
	}

	/**
	 * 根据用户id查询在redis中查询用户对象
	 * 
	 * @param userId
	 * @return
	 */
	private User getUserByUserIdFromRedis(Integer userId) {
		LinkedHashMap<String, Object> userMap = redisHashMapService.get(UserRedisKeyPrefixEnum.USER.getValue() + userId,
				"user");
		User user = parseUser(userMap);
		return user;
	}

	/**
	 * @param userMap
	 * @return
	 */
	private User parseUser(LinkedHashMap<String, Object> userMap) {
		String userStr = JSONObject.toJSONString(userMap);
		User user = JSONObject.parseObject(userStr, User.class);
		return user;
	}

	/**
	 * 登录验证
	 * 
	 * @param webToken
	 * @return
	 */
	public boolean loginCheck(String webToken) {
		if (StringUtils.isEmpty(webToken)) {
			return false;
		}
		Integer userId = (Integer) WebTokenUtil.parseWebToken(webToken, "userId");
		String token = redisObjStringService.get(UserRedisKeyPrefixEnum.USER_ID.getValue() + userId);
		if (StringUtils.isEmpty(token)) {
			log.info("登录验证失败！");
			return false;
		}
		// redisObjStringService.set(UserRedisKeyPrefixEnum.USER_ID.getValue() + userId,
		// token);
		return true;
	}

	/**
	 * 退出登录
	 * 
	 * @param webToken
	 * @return
	 */
	public boolean logout(String webToken) {
		Integer sysId = (Integer) WebTokenUtil.parseWebToken(webToken, "userId");
		if (sysId == null) {
			log.error("UserService logout Exception: 解析webToken异常！");
			return false;
		}
		redisObjStringService.remove(UserRedisKeyPrefixEnum.USER_ID.getValue() + sysId);
		return true;

	}

	/**
	 * 判断指定用户是否有未完成的流程
	 * 
	 * @param userId
	 * @return 有：返回true，无：返回 false
	 */
	public boolean isHaveUnfinishProcess(Integer userId) {
		List<Integer> deptIds = deptService.findVirDept(userId);
		if (deptIds.isEmpty()) {
			return false;
		}
		List<Integer> projectIds = deptService.findProjectByDeptIds(deptIds);
		if (projectIds.isEmpty()) {
			return false;
		}

		if (constructionBaseService.hasNotFinishedByProjectIds(projectIds)) {
			return true;
		}

		return false;
	}

	/**
	 * 获取指定用户的部门信息
	 * 
	 * @param userId
	 * @return
	 */
	public UserDeptId findDept(Integer userId) {
		UserDeptId deptId = new UserDeptId();
		// 查询实体部门
		List<Integer> realDeptIds = deptUserMapper.selectDeptIdByUserIdAndDeptType(userId,
				DeptTypeEnum.DEPT.getValue());
		if (!realDeptIds.isEmpty()) {
			Integer realDeptId = realDeptIds.get(0);
			List<Integer> selfAndPIds = deptService.findAncestors(realDeptId);
			deptId.setRealDeptId(selfAndPIds);
		}
		// 查询虚拟部门
		List<Integer> virDeptIds = deptUserMapper.selectDeptIdByUserIdAndDeptType(userId,
				DeptTypeEnum.VIR_DEPT.getValue());
		if (!virDeptIds.isEmpty()) {
			List<List<Integer>> deptIdList = new ArrayList<>();
			for (Integer id : virDeptIds) {
				List<Integer> selfAndPIds = deptService.findAncestors(id);
				deptIdList.add(selfAndPIds);
			}
			deptId.setVirDeptIds(deptIdList);
		}
		return deptId;
	}

	/**
	 * 判断实体部门唯一性
	 * 
	 * @param deptIds
	 * @return
	 */
	public boolean checkDept(List<Integer> deptIds) {
		int num = 0;
		for (Integer id : deptIds) {
			Dept dept = deptMapper.selectByPrimaryKey(id);
			if (dept == null) {
				log.error("UserService checkDept Exception: 部门不存在！");
				return false;
			}
			if (dept.getDeptType() == DeptTypeEnum.DEPT.getValue()) {
				num++;
			}
			if (num > 1) {
				return false;
			}
		}
		return true;
	}

	/**
	 * 将Integer数组去重
	 * 
	 * @param roleIds
	 * @return
	 */
	public List<Integer> uniq(List<Integer> roleIds) {
		HashSet<Integer> h = new HashSet<Integer>(roleIds);
		roleIds.clear();
		roleIds.addAll(h);
		return roleIds;
	}

	/**
	 * 获取指定用户实体部门关系集合
	 * 
	 * @param userId
	 * @return
	 */
	public List<Map<String, Object>> findRealDepts(Integer userId) {

		List<DeptUser> deptUsers = deptUserMapper.selectByUserIdAndDeptType(userId, DeptTypeEnum.DEPT.getValue());
		List<Map<String, Object>> list = new ArrayList<>();
		for (DeptUser du : deptUsers) {
			Map<String, Object> map = deptService.getrealDeptTree(du.getDeptId());
			list.add(map);
		}
		return list;
	}

	public boolean checkOldPassword(String userName, String pwd) {
		pwd = MD5.md5(pwd);
		User user = userMapper.selectByUnameAndPasswd(userName, pwd);
		if (user == null) {
			log.info("用户名，密码错误！");
			return false;
		}
		return true;
	}

	/**
	 * 修改密码
	 * 
	 * @param userId
	 * @param password
	 * @return
	 */
	public boolean changePassword(Integer userId, String password) {
		User user = new User();
		user.setUserId(userId);
		user.setPasswd(MD5.md5(password));
		if (userMapper.updateByPrimaryKeySelective(user) < 1) {
			log.error("UserService changePassword Exception: 修改异常！");
			return false;
		}
		return true;
	}

	/**
	 * 读取excel文件并保存到数据库
	 * 
	 * @param wb
	 * @param sheetIndex
	 *            sheet页下标：从0开始
	 * @param startReadLine
	 *            开始读取的行:从0开始
	 * @param tailLine
	 *            去除最后读取的行
	 */
	@Transactional(propagation = Propagation.NOT_SUPPORTED)
	public Boolean readExcelToDb(Workbook wb, int sheetIndex, int startReadLine, int tailLine) {

		Sheet sheet = wb.getSheetAt(sheetIndex);
		Row row = null;

		int roleId = 0;
		Row title = sheet.getRow(0);
		for (Cell t : title) {
			String ss = getMergedRegionValue(sheet, title.getRowNum(), t.getColumnIndex());
			System.out.print(ss + "  ");
			roleId = RoleNameEnum.getDescByValue(ss);
		}

		for (int i = startReadLine; i < sheet.getLastRowNum() - tailLine + 1; i++) {
			LinkedHashMap<Integer, String> map = new LinkedHashMap<>();
			String rs = "";

			int num = 0;
			row = sheet.getRow(i);
			for (Cell c : row) {
				boolean isMerge = ExcelUtils.isMergedRegion(sheet, i, c.getColumnIndex());
				// 判断是否具有合并单元格
				if (isMerge) {
					rs = getMergedRegionValue(sheet, row.getRowNum(), c.getColumnIndex());
				} else {
					rs = ExcelUtils.getCellValue(c);
				}
				rs = rs.replaceAll("\\s*", "");
				map.put(num, rs);
				num++;
			}
			try {
				// 将map转为user对象存入数据库
				List<Integer> lists = new ArrayList<>();
				// 1.判断部门和虚拟组是否存在
				Dept dept = deptMapper.selectByDeptName(1, map.get(0));
				if (dept == null) {
					int dId = addOrUpdateDept(map, 1);
					lists.add(dId);
				} else {
					lists.add(dept.getDeptId());
				}

				if (!("".equals(map.get(1))) && map.get(1).trim().length() > 0 && !(map.get(1).equals(map.get(0)))) {
					Dept deptGroup = deptMapper.selectByDeptName(2, map.get(1));
					if (deptGroup == null) {
						int dId = addOrUpdateDept(map, 2);
						lists.add(dId);
					} else {
						lists.add(deptGroup.getDeptId());
					}
				}

				// 2.根据用户名和状态判断用户是否存在；
				String nameCh = map.get(2);
				int nameSplit = nameCh.indexOf("(")  +  nameCh.indexOf("（") + 1;
				if (nameSplit != -1) {
					nameCh = nameCh.substring(0, nameSplit);
				}
				List<User> users = userMapper.selectByName(nameCh);
				if(users.size()>0){
					for (User user : users) {
						//判断手机号是否一致,一致说明是同一个人，不做任何修改，不一致新增
						if(!user.getMobile().equals(PinYinUtil.toUserName(map.get(5)))){
							ReqUser reqUser = addOrUpdateUser(map,2,lists,roleId);
							addUser(reqUser);
						}
					}
				}else{
					ReqUser reqUser = addOrUpdateUser(map,1,lists,roleId);
					addUser(reqUser);
				}
			} catch (Exception e) {
				log.error("UserService readExcelToDb Exception: 数据操作异常");
			}
		}
		return true;
	}

	/**
	 * 封装添加或修改时需要向后台传的对象 读取excel时用
	 * 
	 * @param map
	 * @param type
	 *            1:实体部门 2.虚拟组
	 * @param map
	 */
	public Integer addOrUpdateDept(LinkedHashMap<Integer, String> map, int type) {
		ReqDept reqDept = new ReqDept();
		if (type == 1) {
			reqDept.setParentId(1);
			reqDept.setDeptName(map.get(0));
			reqDept.setDeptType(1);
			reqDept.setDeptDesc(map.get(0));
		} else {
			Dept deptObj = deptMapper.selectByDeptName(1, map.get(0));
			reqDept.setParentId(deptObj.getDeptId());
			reqDept.setDeptName(map.get(1));
			reqDept.setDeptType(2);
			reqDept.setDeptDesc(map.get(1));
		}
		reqDept.setDeptOrder(1);
		deptService.addDept(reqDept);
		return reqDept.getDeptId();
	}

	/**
	 * 封装添加或修改时需要向后台传的对象 读取excel时用
	 * 
	 * @param map
	 * @param type
	 *            1:新增 2.用户姓名相同，但不是同一人时的新增
	 * @param lists
	 * @param roleId
	 * @return
	 */
	public ReqUser addOrUpdateUser(LinkedHashMap<Integer, String> map, int type, List<Integer> lists, int roleId) {
		ReqUser reqUser = new ReqUser();
		String order;
		String position= "";
		String nameMap = map.get(2);
		//南元元（管培生） name:南元元; Position：管培生;没有括号注明普通员工
		if (type == 1) {
			reqUser.setUserName(PinYinUtil.toUserName(map.get(2)));
			reqUser.setName(map.get(2));
		} else {
			List<User> list = userMapper.selectByName(map.get(2));
			order = String.valueOf(list.size() + 1);
			StringBuffer userName = new StringBuffer();
			userName.append(PinYinUtil.toUserName(map.get(2)));
			userName.append(order);
			reqUser.setUserName(userName.toString());

			int num = nameMap.indexOf("(")  +  nameMap.indexOf("（") + 1;
			int lastNum = nameMap.indexOf(")")  +  nameMap.indexOf("）") + 1;
			if (num != -1 && lastNum != -1) {
				String name = nameMap.substring(0, num);
				position = nameMap.substring(num+1,lastNum);
				reqUser.setName(name);
			}
		}
        reqUser.setPosition(position.length()>0?position:"普通员工");

		reqUser.setTel(map.get(4));
		reqUser.setMobile(map.get(5));
        reqUser.setRoleIds(new ArrayList<>(roleId));
        reqUser.setDeptIds(lists);
		reqUser.setEmail(" ");
		return reqUser;
	}

	public void hiddenManagerMobile(List<UserRoleBean> list) {
		for (UserRoleBean user : list) {
			if (user.getIsManager()) {
				user.setMobile("");
			}
		}

	}

	/**
	 * 查询指定用户的所有角色Id
	 * 
	 * @param userId
	 * @return
	 */
	public List<Integer> findRoles(Integer userId) {
		List<Integer> roleIds = new ArrayList<Integer>();
		
		List<Integer> roleIdList = userRoleMapper.selectRoleIdByUserId(userId); 
		List<Integer> userGroupIds = userGroupUserMapper.selectUserGroupIdByUserId(userId);
		if(!userGroupIds.isEmpty()) {
			List<Integer> userGroupRoleIds = userGroupRoleMapper.selectRoleIdByUserGroupIds(userGroupIds);
			roleIds.addAll(userGroupRoleIds);
		}
		
		roleIds.addAll(roleIdList);
		return uniq(roleIds);
	}

	

}
